package com.gzy.wb.controller;

import com.gzy.wb.core.R;
import com.gzy.wb.model.User;
import com.gzy.wb.server.AuthServer;
import com.gzy.wb.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin
@RestController
public class AuthController {

    @Autowired
    AuthServer server;
    @Autowired
    UserServer userServer;

    // query  ?xxxxx=111 @RequestParam String username,@RequestParam String password
    // 请求体
    @PostMapping("/login")
    R<String> login(@RequestBody LoginPara para){
        String token = server.login(para.username,para.password);

        R<String> r = new R();
        r.setCode(R.Code.OK);
        r.setMessage("登录成功");
        r.setData(token);
        return r;
    }

    @PostMapping("/signup")
    R<String> signup(@RequestBody LoginPara para){
        server.signup(para.username,para.password);

        R<String> r = new R();
        r.setCode(R.Code.OK);
        r.setMessage("注册成功");
        return r;
    }

    @PostMapping("/auth/logout")
    R logout(){
        return new R();
    }


    //@Secured("ROLE_USER")
    @GetMapping("/userinfo")
    R<User> userinfo(@AuthenticationPrincipal UserDetails user){
        String username = user.getUsername();

//        User user = server.checkJWT(token);
//        return new R<User>(){{
//            setData(user);
//        }};
        User userByName = userServer.findUserByName(username);
        return new R(){{
            setData(userByName);
            setMessage("ok");
            setCode(Code.OK);
        }};
    }

    @Secured("ROLE_ADMIN")
    @GetMapping("/userinfo1")
    R<User> userinfo1(String token){
        User user = server.checkJWT(token);
        return new R<User>(){{
            setData(user);
        }};
    }

    @GetMapping("/userinfo2")
    R<User> userinfo2(String token){
        User user = server.checkJWT(token);
        return new R<User>(){{
            setData(user);
        }};
    }

}

class LoginPara{
     String username;
     String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
